var express = require('express');
var router = express.Router();
var { user_model } = require("../utils/model")
var { aesEncrypt } = require("../utils")
/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});

router.get("/demo", (req, res) => {
  res.send("<h4>ARe you OK coders ????</h4>")
})

router.get("/data", (req, res) => {
  res.json({
    code: 200,
    type: 1,
    msg: "获取数据成功-data-data - data "
  })
})


router.all("/login", (req, res) => {
  var query = req.query;
  console.log(query)
  user_model.findOne({
    username: query.username,
  })
    .then(result => {
      if (result) {
        if (result.pass == query.pass) {
          // 登陆成功 存储用户信息
          req.session.username = result.username
          req.session.phone = result.phone
          // res.send("<script>alert('登陆成功')</script>");
          res.redirect("/")
        } else {
          res.send("<script>alert('登陆失败,用户名和密码不匹配');location.href='/login'</script>")
        }
      } else {
        res.send("<script>alert('当前用户不存在');location.href='/login'</script>")
      }
    })
    .catch(err => {
      res.send("<script>alert('服务器异常,请重试');location.href='/register'</script>")
    })

})

router.all("/register", (req, res) => {
  var body = req.body
  console.log(body)
  // 插入注册 
  user_model.findOne({
    username: body.username
  })
    .then(data => {
      if (data) {
        // 提示已经注册
        res.send("<script>alert('当前用户已经被注册,请重新注册!');location.href='/register'</script>")
      } else {
        // 没有注册 可以直接插入 
        body.time = new Date();
        user_model.insertMany(body)
          .then(result => {
            res.send(`<script>alert('注册成功!,前往登陆.');location.href='/login?username=${aesEncrypt(body.username)}'</script>`)
          })
      }
    })
    .catch(err => {
      res.send("<script>alert('服务器异常,请重试');location.href='/register'</script>")
    })

})


// ajax 最好返回json 
router.all("/signin", (req, res) => {
  var body = req.body;
  user_model.findOne({
    ...body
  })
    .then(result => {
      if (result) {
        res.json({
          code: 200,
          msg: '登陆成功',
          body,
          result
        })
      } else {
        res.json({
          code: 1001,
          msg: '登陆失败',
        })
      }
    })
    .catch(err => {
      res.json({
        code: 500,
        msg: '服务器异常',
        err
      })
    })

})


module.exports = router;
